package com.soundai.skill.helloworld.Service;

import com.soundai.skill.helloworld.HttpHelper.HttpClientHelper;
import com.soundai.skill.helloworld.baiduApi.ApiNlpDataHelper;
import com.soundai.skill.helloworld.config.uriConfig;
import com.soundai.skill.helloworld.helper.TextConvertNumber;
import com.soundai.skill.helloworld.log.logC;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.json.JSONException;
import redis.clients.jedis.Jedis;

import java.io.UnsupportedEncodingException;

/**
 * TODO：商城购物处理结构
 * DATE：2019-07-18
 * By  ：YanPeixin
 */
public class ShoppingService {



    /**
     * 查询商品接口 NLP
     * @param speek
     * @return
     */
    public static JSONObject productInfo(String speek) throws  JSONException{
        //public static String productInfo(String speek) throws  JSONException{
        String vValue = ApiNlpDataHelper.getWords(speek, "v").trim().toString();  //动词
        String mValue = ApiNlpDataHelper.getWords(speek, "m").trim().toString(); //量词
        //名称
        String nValue = ApiNlpDataHelper.getWords(speek, "n").trim().toString();
        try {
            nValue = java.net.URLEncoder.encode(nValue, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String doGetUrl = String.format(uriConfig.shopQueryProductUrl, nValue);
        String getProduceList = HttpClientHelper.doGet(doGetUrl);
        JSONObject jsonObject = JSONObject.fromObject(getProduceList);
        JSONArray arr = JSONArray.fromObject(jsonObject);
        //return arr.getJSONObject(0).get("Data").toString();


        JSONArray arrProduct = JSONArray.fromObject(arr.getJSONObject(0).get("Data"));
        JSONObject json = new JSONObject();
        json.put("data",arrProduct); //商品列表数据
        json.put("todo", getMoreProductTxt(arrProduct)); ///播放商品字符串
        json.put("buyNum",TextConvertNumber.chineseNumber2Int(mValue));//购买数量
        //获取AI识别反馈
        //JSONObject aiJson = AIService.getAiInfo(area,action);
        json.put("ai", AIService.getAiInfo("shopping","queryProduct"));
        json.put("area", "shopping");//购买领域
        json.put("action", "waitConfrim");//等待确认
        return json;

    }

    /***
     *  用户确认交互
     * @param speek
     * @return
     */
    public static JSONObject waitConfrim(String speek){
        JSONObject returnMsg = new JSONObject();
        String mValue = null;
        try {
            mValue = ApiNlpDataHelper.nlpResult(speek, "m").trim().toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        int buyNum = 0;
        int selectTypeNum = 0;
        if(mValue.indexOf(",")>=0){
            String[] arrStr = mValue.split(",");
            selectTypeNum = TextConvertNumber.chineseNumber2Int(arrStr[0]);
            buyNum = TextConvertNumber.chineseNumber2Int(arrStr[1]);
        }else{
            buyNum = TextConvertNumber.chineseNumber2Int(mValue);
        }
        //连接本地缓存
        Jedis jedis = new Jedis("localhost");
        String data = jedis.get("data").toString();
        JSONObject jsonRedisData = JSONObject.fromObject(data);
        returnMsg.put("data",jsonRedisData.get("data").toString());//商品列表
        returnMsg.put("selectTypeNum",selectTypeNum);//选择第几个商品
        returnMsg.put("buyNum",buyNum);//购买数量
        returnMsg.put("ai", AIService.getAiInfo("shopping","waitConfrim"));
        returnMsg.put("area", "shopping");//购买领域
        returnMsg.put("action", "order");//下一个动作等待下单
        String productName = getProductName(selectTypeNum,jsonRedisData.get("data").toString());
        returnMsg.put("todo", "您确定购买第"+selectTypeNum+"种商品,"+getProductName(selectTypeNum,jsonRedisData.get("data").toString())+buyNum+"吗？"); ///播放商品字符串
        return returnMsg;
    }


    /**
     * 创建订单
     * @return
     */
     public  static  JSONObject createOrder(){
         JSONObject returnMsg = new JSONObject();
         //获取并解析缓存的数据
         Jedis jedis = new Jedis("localhost");
         String data = jedis.get("data").toString();
         JSONObject jsonRedis =  JSONObject.fromObject(data);

         int selectTypeNum = Integer.parseInt(jsonRedis.get("selectTypeNum").toString());
         int buyNum = Integer.parseInt(jsonRedis.get("buyNum").toString());
         String productData = jsonRedis.get("data").toString();

             //************************************************************音响绑定的用户信息目前暂时没有/*********************************************************************************************************
             String orderResult = toOrder(selectTypeNum,"77777",productData,buyNum);
             String ss = "";
             if(!orderResult.equals(""))
             {
                 orderResult = orderResult.replace("\r\n","").replace("\\","").replace("\"","");
             }
             JSONObject arr = JSONObject.fromObject(orderResult);
             String todo = "";
             String  success = arr.get("success").toString();
             if(success.equals("true")){
                 //todo = "已为您下单成功,订单号"+arr.get("orderIds").toString()+"请及时付款";
                 todo = "下单成功,单号"+arr.get("orderIds").toString()+"请您及时付款";
             }else
             {
                 todo = arr.get("orderIds").toString();
             }
             returnMsg.put("data",orderResult);//购买数量
             returnMsg.put("todo", todo); ///播放商品字符串
             returnMsg.put("selectTypeNum",selectTypeNum);//选中种类
             returnMsg.put("buyNum",buyNum);//购买数量
             returnMsg.put("ai", AIService.getAiInfo("shopping","order"));
             returnMsg.put("area", "shopping");//购买领域
             returnMsg.put("action", "pay");//下一个动作等待下单
             return  returnMsg;
     }


    /**
     * 选购商品下单
     * @param userId
     * @param productInfo
     * @return
     */
    public static String toOrder(int selectTypeNum,String userId,String productInfo,int buyNum){

        JSONArray resultJson = JSONArray.fromObject(JSONObject.fromObject(productInfo).get("data"));
        String skuId = "";
        for (int i=(selectTypeNum-1);i<resultJson.size();i++) {
            JSONObject myjObject = JSONObject.fromObject(resultJson.get(i));
            skuId = myjObject.get("SkuId").toString();
        }

        //String createOrder = HttpClientHelper.doPost("http://47.107.66.121:9988/api/Order/SubmitOrder?productSku=1769_0_0_0&buyAmount=1&buyUserId=77777","");
        String doPostOrderUrl = String.format(uriConfig.toOrderUrl,skuId,buyNum,userId);
        logC.writeFile("","执行下单地址："+doPostOrderUrl);
        String createOrder = HttpClientHelper.doPost(doPostOrderUrl,"");
        return  createOrder;
    }

    /**
     * 获取对应推荐商品的名称
     * @param selectTypeNum 选择商品所在位置
     * @param productInfo   商品信息列表
     * @return
     */
    public static String getProductName(int selectTypeNum,String productInfo){
        JSONArray resultJson = JSONArray.fromObject(productInfo);
        String ProductName = "";
        for (int i=(selectTypeNum-1);i<resultJson.size();i++) {
            JSONObject myjObject = JSONObject.fromObject(resultJson.get(i));
            ProductName = myjObject.get("ProductName").toString();
        }
        return ProductName;
    }


    /**
     * 拼接商品字符串，用于音箱播放（推荐一种商品）
     * @param arrProduct
     * @return
     */
    public static  String getOneProductTxt(JSONArray arrProduct){

        String strAppendProduct = "";
        for (int k=0;k<arrProduct.size();k++){
            JSONObject joProduct = JSONObject.fromObject(arrProduct.get(k));
            if(k==0)
                strAppendProduct += "第"+(k+1)+"种,"+joProduct.get("ProductName")+joProduct.get("SalePrice")+"元";
            else
                strAppendProduct += ",第"+(k+1)+"种,"+joProduct.get("ProductName")+joProduct.get("SalePrice")+"元";
        }
        logC.writeFile("","合成商品播放：：："+strAppendProduct+" ******** "+arrProduct.toString());
        String returnProText = "";
        if(!strAppendProduct.equals("")){
            returnProText = "为您推荐商品为，"+strAppendProduct +"，请确定选购";
        }
        return  returnProText;
    }

    /**
     * 拼接商品字符串，用于音箱播放 （存在多种商品推荐）
     * @param arrProduct
     * @return
     */
    public static  String getMoreProductTxt(JSONArray arrProduct){
        String strAppendProduct = "";
        for (int k=0;k<arrProduct.size();k++){
            JSONObject joProduct = JSONObject.fromObject(arrProduct.get(k));
            if(k==0) {
                strAppendProduct += "第" + (k + 1) + "种," + joProduct.get("ProductName") + joProduct.get("SalePrice") + "元";
            }
            else {
                strAppendProduct += ",第" + (k + 1) + "种," + joProduct.get("ProductName") + joProduct.get("SalePrice") + "元";
            }
        }
        logC.writeFile("","合成商品播放：：："+strAppendProduct+" ******** "+arrProduct.toString());
        String returnProText = "";
        if(!strAppendProduct.equals("")){
            returnProText = "为您推荐商品有"+arrProduct.size()+"种，"+strAppendProduct +"，请选择并确认购买数量";
        }
        return  returnProText;
    }

    /**
     * 返回值
     * @param data
     * @param todo
     * @param selectTypeNum
     * @param buyNum
     * @return
     */
        public static JSONObject responeVal(String data,String todo,Object selectTypeNum,Object buyNum){
            JSONObject returnMsg = new JSONObject();
            returnMsg.put("data",data);
            returnMsg.put("todo", todo); ///播放商品字符串
            returnMsg.put("selectTypeNum",selectTypeNum);//选中种类
            returnMsg.put("buyNum",buyNum);//购买数量
            //returnMsg.put("ai", AIService.getAiInfo("shopping","order"));
            //returnMsg.put("area", "shopping");//购买领域
            //returnMsg.put("action", "pay");//下一个动作等待下单*/
            return returnMsg;
        }


}
